package com.ce.sys.ftp;

import java.util.ArrayList;
import java.util.List;

import sun.net.ftp.FtpClient;

public class FtpDownClientSource {
	
	private String ip,username,pwd;
	
	private int minClient,maxClient,step;
	
	private List<FtpClient> list = new ArrayList<FtpClient>();

	public FtpDownClientSource(String ip, String username, String pwd) {
		super();
		this.ip = ip;
		this.username = username;
		this.pwd = pwd;
		this.minClient = 5;
		this.maxClient = 100;
		this.step = 5;
		this.createClient(minClient);
	}

	private int createClient(int num){
		int cnt = 0;
		FtpClient ftp = null;
		for(int i=0;i<num && list.size()<=maxClient;i++){
			ftp = this.createClient();
			list.add(ftp);
			cnt++;
		}
		return cnt;
	}

	private FtpClient createClient(){

		DownFtpClient ftp_ = null;
		try {
			ftp_ = new DownFtpClient(ip);
			ftp_.login(username, pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ftp_;
	}
	
	public FtpClient getFtpClient(){
		DownFtpClient client = null;
		for(int i=0;i<list.size();i++){
			client = (DownFtpClient) list.get(i);
			if(!client.serverIsOpen()){
				list.remove(i--);
			}
			if(client.isFree())
				return client;
		}
		if(list.size()<maxClient && this.createClient(step)>0)
			return this.getFtpClient();
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	public int getMaxClient() {
		return maxClient;
	}

	public void setMaxClient(int maxClient) {
		this.maxClient = maxClient;
	}

	public int getMinClient() {
		return minClient;
	}

	public void setMinClient(int minClient) {
		this.minClient = minClient;
	}

	public int getStep() {
		return step;
	}

	public void setStep(int step) {
		this.step = step;
	}

}
